<template>
  <div class="advertising-index">
    <a-form-model ref="ruleForm" :rules="rules" :model="ruleForm">
      <a-row justify="space-between">
        <a-col :span="8">
          <a-form-model-item has-feedback label="名称" prop="slotName" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 1 }">
            <a-input v-model="ruleForm.slotName" allow-clear placeholder="请输入" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item has-feedback label="所属媒体" prop="appName" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 1 }">
            <a-input v-model="ruleForm.appName" allow-clear placeholder="请输入" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8" push="5">
          <a-form-model-item>
            <a-space>
              <a-button @click="resetForm('ruleForm')"> 重置 </a-button>
              <a-button :loading="isLoading" type="primary" @click="submitForm('ruleForm')"> 查询 </a-button>
            </a-space>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-row justify="space-between">
      <a-col :span="8">
        <h3>详情列表</h3>
      </a-col>
      <a-col :span="8" offset="8" push="5">
        <a-button type="primary" icon="plus" @click="handleAddMedia('新建广告位')"> 新建广告位 </a-button>
        <util-modules @refresh="refreshData" @densityChange="densityChange" />
      </a-col>
    </a-row>
    <a-table
      :pagination="false"
      class="my-table"
      :loading="isLoading"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data-source="data"
      :size="activeSize"
    >
      <!-- <span slot="like">
        <a-icon type="star" style="fontSize: 22px;color:#cdcdcd" v-if="!liked" @click="handleLike" />
        <a-icon type="star" style="fontSize: 22px;color:#f4ea2a" theme="filled" v-if="liked" @click="handleLike" />
      </span> -->
      <span slot="slotName" slot-scope="_, record">
        <a @click="handleAddMedia('广告位设置', record)">{{ record.slotName }}</a>
      </span>
      <span slot="topTime" slot-scope="_, record">
        <!-- 未高亮 -->
        <a-icon
          type="star"
          style="fontsize: 22px; color: #cdcdcd"
          v-if="[0].includes(record.topTime)"
          @click="handleLike(record.topTime, record.slotKey)"
        />
        <!-- 已经高亮的 -->
        <a-icon
          type="star"
          style="fontsize: 22px; color: #f4ea2a"
          theme="filled"
          v-else
          @click="handleLike(record.topTime, record.slotKey)"
        />
      </span>
      <span slot="action" slot-scope="_, record">
        <a @click="handleOpenProject(record)">在投计划</a>
        <a-divider type="vertical" />
        <a @click="viewData(record)">查看数据</a>
        <a-divider type="vertical" />
        <a @click="handleOpenIncome(record)">收入</a>
      </span>
      <span slot="link" slot-scope="_, record">
        <a @click="handleCapllyLink(record.slotUrl)">查看</a>
      </span>
    </a-table>
    <a-row class="pagination">
      <a-pagination
        show-size-changer
        :default-current="pageNo"
        :defaultPageSize="100"
        :total="total"
        :show-total="(total, range) => `第${range[0]} - ${range[1]}条/总共${total}条`"
        show-less-items
        :page-size-options="['10', '20', '50', '100']"
        @change="handleCurrentChange"
        @showSizeChange="handleSizeChange"
      />
    </a-row>
    <!-- modal -->
    <!-- 新建-->
    <a-modal v-model="visible" :title="setAdvertising" on-ok="handleOk" @cancel="handleCancel">
      <a-form-model ref="dynamicValidateForm" labelAlign="left" :model="AdvertisingForm" :label-col="labelCol" :wrapper-col="wrapperCol">
        <div>
          <h2>基本信息</h2>
          <a-form-model-item label="广告位名称:">
            <a-input v-model="AdvertisingForm.slotName" />
          </a-form-model-item>
          <a-form-model-item v-if="!soldOutVisible" label="所属媒体:">
            <a-select v-model="AdvertisingForm.appKey" placeholder="请选择">
              <a-select-option v-for="item in AppListData" :key="item.appKey" :value="item.appKey">
                {{ item.appName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="广告位类型:" v-if="!soldOutVisible">
            <a-select v-model="AdvertisingForm.slotType" @change="adverTypeChange" placeholder="请选择">
              <a-select-option value="0"> 互动广告位 </a-select-option>
              <a-select-option value="2"> 展示广告位 </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item v-if="materialVisible" label="素材类型:">
            <a-select v-model="AdvertisingForm.materialType" placeholder="请选择">
              <a-select-option value="0"> bannar </a-select-option>
              <a-select-option value="1"> icon </a-select-option>
              <a-select-option value="2"> 弹窗 </a-select-option>
            </a-select>
          </a-form-model-item>
        </div>
        <div>
          <h2>互动场景配置</h2>
          <a-form-model-item label="活动逻辑:">
            <a-radio-group v-model="AdvertisingForm.activityRecommendType" @change="activityRecChange">
              <a-radio value="0"> 系统推荐 </a-radio>
              <a-radio value="1"> 自选活动 </a-radio>
            </a-radio-group>
            <a-select
              :disabled="actVisible"
              mode="multiple"
              size="default"
              placeholder="选择用户可参与的活动"
              v-model="catListValue"
              @change="handleChange1"
            >
              <a-select-option v-for="item in CatListData" :key="item.id">
                {{ item.activityName }}
              </a-select-option>
            </a-select>
            <!-- <a-input v-model="AdvertisingForm.selectedActivities" /> -->
          </a-form-model-item>
          <a-form-model-item label="特殊设置:">
            <a-checkbox-group v-model="actvalue">
              <a-row>
                <a-checkbox value="1"> 进入活动自动弹出广告券 </a-checkbox>
              </a-row>
            </a-checkbox-group>
            <a-checkbox-group v-model="extvalue">
              <a-row>
                <a-checkbox value="1"> 自动抽取第三张广告券 </a-checkbox>
              </a-row>
            </a-checkbox-group>
            <a-checkbox-group v-model="cutvalue">
              <a-row>
                <a-checkbox value="1"> 点击有奖引导切换活动(多活动时生效) </a-checkbox>
              </a-row>
            </a-checkbox-group>
          </a-form-model-item>
        </div>
        <div>
          <h2>直投广告位配置</h2>
          <a-form-model-item label="直投计划:">
            <a-select v-model="AdvertisingForm.directAdvertPlan" placeholder="需要直投时请选择计划">
              <a-select-option value="buzhitou"> 不直投 </a-select-option>
              <a-select-option v-for="item in AdverPlanListData" :key="item.id" :value="item.id">
                {{ item.planName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </div>
      </a-form-model>
      <template slot="footer">
        <a-popconfirm @confirm="soldOutConfirm" title="下架后不可恢复，请谨慎操作。是否确认下架？" ok-text="确定" cancel-text="取消">
          <a-button v-if="soldOutVisible" type="danger">下架</a-button>
        </a-popconfirm>

        <a-button key="back" @click="handleCancel('dynamicValidateForm')"> 取消 </a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleOk"> 保存 </a-button>
      </template>
    </a-modal>
    <!-- 查看 -->
    <a-modal v-model="linkVisible" title="请复制地址" @ok="handleLinked">
      <a-textarea v-model="siteLink" readonly="readonly" :auto-size="{ minRows: 2, maxRows: 6 }" />
    </a-modal>
    <!-- 在投计划 -->
    <a-modal class="inCast" width="55%" :footer="null" :destroyOnClose="true" v-model="projectVisible" title="在投计划" @ok="handleProject">
      <!-- 优先计划 -->
      <div class="planTable" ref="pl">
        <a-row>
          <a-col :span="8"><h3>优先计划</h3></a-col>
          <a-col :span="8" offset="8" push="6">
            <a-button type="primary" @click="saveSlotAdberList"> 保存 </a-button>
          </a-col>
        </a-row>
        <a-table
          class="jihua"
          size="middle"
          :rowKey="(record) => record.id"
          :pagination="false"
          :columns="projectColumn"
          :data-source="projectData"
        >
          <span slot="sortrank">
            <a-icon style="font-size: 25px" type="unordered-list" />
          </span>
          <span slot="planName" slot-scope="_, record">
            <a @click="toDetail(record.id)">
              {{ record.planName }}
            </a>
          </span>
          <span slot="planLandUrl" slot-scope="_, record">
            <a-popover title="">
              <template slot="content">
                <img style="width: 200px; height: 200px" :src="record.materialList[0].bannerImg" />
              </template>
              <img style="width: 50px; height: 50px" :src="record.materialList[0].bannerImg" />
            </a-popover>
          </span>
          <span slot="planStatus" slot-scope="_, record">
            <a-badge v-if="record.planStatus == 0" status="default" text="待开始" />
            <a-badge v-if="record.planStatus == 1" status="processing" text="投放中" />
            <a-badge v-if="record.planStatus == 2" status="error" text="已停止" />
          </span>
          <span slot="action" slot-scope="_, record">
            <a-icon @click="downData(record)" type="down" />
            <a-divider type="vertical" />
            <a @click="planYouXian(record)">拉黑</a>
          </span>
        </a-table>
      </div>
      <!-- 自动排序计划 -->
      <div class="pl-box">
        <a-row class="planTableRow">
          <a-col :span="8"><h3>自动排序计划</h3></a-col>
        </a-row>
        <a-table
          class="jihua"
          size="middle"
          :rowKey="(record) => record.id"
          :pagination="false"
          :columns="projectColumns"
          :data-source="selfProjectData"
        >
          <span slot="sortrank">
            <span>-</span>
          </span>
          <span slot="planName" slot-scope="_, record">
            <a @click="toDetail(record.id)">
              {{ record.planName }}
            </a>
          </span>
          <span slot="planLandUrl" slot-scope="_, record">
            <a-popover title="">
              <template slot="content">
                <img style="width: 200px; height: 200px" :src="record.materialList[0].bannerImg" />
              </template>
              <img style="width: 50px; height: 50px" :src="record.materialList[0].bannerImg" />
            </a-popover>
          </span>
          <span slot="planStatus" slot-scope="_, record">
            <a-badge v-if="record.planStatus == 0" status="default" text="待开始" />
            <a-badge v-if="record.planStatus == 1" status="processing" text="投放中" />
            <a-badge v-if="record.planStatus == 2" status="error" text="已停止" />
          </span>
          <span slot="action" slot-scope="_, record">
            <a-icon @click="upData(record)" type="up" />
            <a-divider type="vertical" />
            <a @click="planZiDong(record)">拉黑</a>
          </span>
        </a-table>
      </div>
      <!-- 黑名单 -->
      <div>
        <a-row class="planTableRow">
          <a-col :span="8"><h3>黑名单</h3></a-col>
        </a-row>
        <a-table
          size="middle"
          :rowKey="(record) => record.id"
          :pagination="false"
          :columns="projectColumns"
          :data-source="blackListProjectData"
        >
          <span slot="sortrank">
            <span>-</span>
          </span>
          <span slot="planName" slot-scope="_, record">
            <a @click="toDetail(record.id)">
              {{ record.planName }}
            </a>
          </span>
          <span slot="planLandUrl" slot-scope="_, record">
            <a-popover title="">
              <template slot="content">
                <img style="width: 200px; height: 200px" :src="record.materialList[0].bannerImg" />
              </template>
              <img style="width: 50px; height: 50px" :src="record.materialList[0].bannerImg" />
            </a-popover>
          </span>
          <span slot="planStatus" slot-scope="_, record">
            <a-badge v-if="record.planStatus == 0" status="default" text="待开始" />
            <a-badge v-if="record.planStatus == 1" status="processing" text="投放中" />
            <a-badge v-if="record.planStatus == 2" status="error" text="已停止" />
          </span>
          <span slot="action" slot-scope="_, record">
            <a @click="planHuiFu(record)">恢复投放</a>
          </span>
        </a-table>
      </div>
    </a-modal>
    <!-- 收入 -->
    <a-modal width="55%" :footer="null" v-model="incomeVisible" title="广告位收益">
      <a-row>
        <h3>{{ incomeTitle }}</h3>
      </a-row>
      <table class="income" cellspacing="0" cellpadding="0">
        <tr style="backgroundcolor: #fafafa">
          <th style="padding: 13px; font-weight: 400" width="400">日期</th>
          <th style="font-weight: 400" width="400">广告位访问UV</th>
          <th style="font-weight: 400" width="200">收入</th>
          <th style="font-weight: 400" width="100">操作</th>
        </tr>
        <tr>
          <td class="incomeTd" colspan="3">
            <a-button type="dashed" style="width: 100%; margin-top: 10px" @click="showIncomeBtn"> + 表格添加一行数据 </a-button>
          </td>
        </tr>
        <tr v-if="addIncomeVisible">
          <td style="padding: 13px">
            <a-date-picker v-model="initSettleTime" :default-value="moment(new Date(), 'YYYY-MM-DD')" format="YYYY-MM-DD" />
          </td>
          <td>
            <a-input-number
              v-model="addIncome.advertValidClick"
              placeholder="请输入"
              :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="(value) => value.replace(/\￥\s?|(,*)/g, '')"
              id="inputNumber"
              :min="0"
            />
          </td>
          <td>
            <a-input-number
              v-model="addIncome.slotIncome"
              :formatter="(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="(value) => value.replace(/\￥\s?|(,*)/g, '')"
              id="inputNumber"
              :min="0"
            />
          </td>
          <td>
            <a type="link" @click="addIncomeBtn(false)">保存</a>
            <a-divider type="vertical" />
            <a type="link" @click="addIncomeVisible = false">取消</a>
          </td>
        </tr>
        <tr v-for="item in incomeData" :key="item.id">
          <td style="padding: 13px">
            <a-date-picker
              v-if="item.edit"
              v-model="initSettleTime"
              :default-value="moment(item.settleTime, 'YYYY-MM-DD')"
              format="YYYY-MM-DD"
            />
            <span v-if="!item.edit">{{ item.settleTime }}</span>
          </td>
          <td>
            <span v-if="!item.edit">{{ item.advertValidClick }}</span>
            <a-input-number
              v-if="item.edit"
              v-model="addIncome.advertValidClick"
              :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="(value) => value.replace(/\￥\s?|(,*)/g, '')"
              id="inputNumber"
              :min="0"
            />
          </td>
          <td>
            <span v-if="!item.edit">{{ item.slotIncome / 100 }}</span>
            <a-input-number
              v-if="item.edit"
              v-model="addIncome.slotIncome"
              :formatter="(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="(value) => value.replace(/\￥\s?|(,*)/g, '')"
              id="inputNumber"
              :min="0"
            />
          </td>
          <td>
            <a type="link" v-if="!item.edit" @click="editIncome(item)">编辑</a>
            <a type="link" v-if="item.edit" @click="item.edit = addIncomeBtn(item)">保存</a>
            <a-divider v-if="item.edit" type="vertical" />
            <a type="link" v-if="item.edit" @click="item.edit = !item.edit">取消</a>
          </td>
        </tr>
      </table>

      <a-row class="pagination">
        <a-pagination
          show-size-changer
          :default-current="incomeObj.pageNo"
          :defaultPageSize="incomeObj.pageSize"
          :total="incomeTotal"
          :show-total="(total, range) => `第${range[0]} - ${range[1]}条/总共${incomeTotal}条`"
          show-less-items
          :page-size-options="['10', '20', '55', '100']"
          @change="handleIncomeCurrentChange"
          @showSizeChange="handleIncomeSizeChange"
        />
      </a-row>
    </a-modal>
    <!-- modal end -->
  </div>
</template>

<script>
import moment from 'moment'
import Big from 'big.js'
import 'moment/locale/zh-cn'
import UtilModules from '_c/UtilModules.vue'
import { columns, projectColumns, projectColumn } from '@/mock/table/table2'
import { toRoute, getTableSize } from '../../lib/utils'
import {
  getSlotList,
  postSlotTop,
  postSlotUnTop,
  getAppList,
  getCatList,
  getAdverPlanData,
  addSlotUpdate,
  soldSlotUpShow,
  getIncomeList,
  AddIncomeList,
  getAdberList,
  getSlotAdberList,
  postSlotAdberList,
} from '@/api/MeidaMan/api'
import Sortable from 'sortablejs'
export default {
  name: 'AdvertisingIndex',
  components: {
    UtilModules,
  },
  data() {
    return {
      _checkId: 0,
      activeSize: '',
      siteLink: '',
      addIncomeVisible: false, // 新增一条收益
      incomeVisible: false, // 收入
      soldOutVisible: false, // 下架按钮
      actVisible: true, //选择用户可参与的活动
      materialVisible: false, // 素材类型显示与隐藏
      projectVisible: false,
      linkVisible: false,
      isLoading: false,
      liked: false,
      loading: false,
      visible: false,
      ruleForm: {
        slotName: '',
        appName: '',
      },
      rules: {},
      columns: [],
      data: [],
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'medias' }),
      pageNo: 1,
      pageSize: 100,
      total: 0,
      slotType: 0,
      // 新建广告位弹窗
      setAdvertising: '',
      labelCol: { span: 5 },
      wrapperCol: { span: 14 },
      AdvertisingForm: {
        slotName: '', // 广告位名称
        appKey: undefined, // 所属媒体
        slotType: '0',
        materialType: '0', // 素材类型
        activityRecommendType: '0', //  活动逻辑
        selectedActivities: '', // 活动逻辑中自选中的活动id,多个用'',''隔开
        popAdvertType: 0, // 进入活动自动弹出广告卷
        autoDrawAdvert: 0, // 自动抽取第三章广告卷
        autoChangeActivity: 0, // 点击有奖引导切换活动(多活动时生效)
        directAdvertPlan: undefined, //直投计划
      },
      AppListData: [], // 所属媒体
      CatListData: [], // 活动列表
      catListValue: [],
      AdverPlanListData: [],
      actvalue: [],
      extvalue: [],
      cutvalue: [],
      slotKey: '',

      // 收入弹窗
      incomeTitle: '',
      incomeData: [],
      incomeTotal: 0,
      incomeObj: {
        pageNo: 1,
        pageSize: 20,
        sk: '',
      },
      moment,
      initSettleTime: null,
      addIncome: {
        id: null,
        settleTime: '',
        advertValidClick: null,
        sk: '',
        slotIncome: '',
      },
      // 在投计划弹窗
      projectColumns,
      projectColumn,
      projectData: [], //优先计划
      selfProjectData: [], // 自动排序
      blackListProjectData: [], // 黑名单
      blackAdverts: '', // 计划拉黑的id
      slotObj: {
        sk: '',
        blackAdverts: [],
        adverts: [],
      }, // 保存
      appKey: '',
    }
  },

  mounted() {
    const date = moment()
    this.initSettleTime = date
    this.columns = columns
    const { appKey } = this.$route.query
    this.appKey = appKey
    this.slotList({ pageNo: this.pageNo, pageSize: this.pageSize, appKey, slotType: this.slotType })
    // 阻止默认行为
    document.body.ondrop = function (event) {
      event.preventDefault()
      event.stopPropagation()
    }
    // this.rowDrop()
  },
  computed: {},
  methods: {
    /**
     * @func 刷新数据
     */
    refreshData() {
      const appKey = this.appKey
      this.slotList({ pageNo: this.pageNo, pageSize: this.pageSize, appKey, slotType: this.slotType })
    },
    /**
     * @func 表格密度
     */
    densityChange(value) {
      const { tableSize } = this.$store.state
      this.activeSize = getTableSize(value, tableSize)
    },
    /**
     * @func 行拖拽
     * */
    rowDrop() {
      this.$nextTick(() => {
        const tbody = document.querySelector('.jihua .ant-table-body .ant-table-tbody')
        const _this = this
        Sortable.create(tbody, {
          onEnd({ newIndex, oldIndex }) {
            const currRow = _this.projectData.splice(oldIndex, 1)[0]
            _this.projectData.splice(newIndex, 0, currRow)
          },
        })
      })
    },
    toDetail(id) {
      toRoute(this, `plan-edit?id=${id}`)
    },
    /**
     * @func 列表数据
     */
    async slotList(param) {
      this.isLoading = true
      try {
        const data = await getSlotList({ ...param })
        if (data) {
          this.isLoading = false
          this.data = data.list
          this.total = data.count
        }
      } catch (err) {
        this.isLoading = false
        this.$msgErr(err.message)
      }
    },
    /**
     *  @func 改变页面值
     */
    handleCurrentChange(page, pageSize) {
      console.log(page)
      this.pageNo = page
      this.pageSize = pageSize
      const { slotName, appName } = this.ruleForm
      const result = { slotName, appName }
      this.slotList({ pageNo: this.pageNo, pageSize: this.pageSize, slotType: this.slotType, ...result })
    },

    /**
     *  @func 改变页面数据多少
     */
    handleSizeChange(current, size) {
      this.pageNo = current
      this.pageSize = size
      const { slotName, appName } = this.ruleForm
      const result = { slotName, appName }
      this.slotList({ pageNo: this.pageNo, pageSize: this.pageSize, slotType: this.slotType, ...result })
    },
    /**
     * @func 广告位置顶
     */
    async slotTop(slotKey) {
      try {
        await postSlotTop({ slotKey })
        const { slotName, appName } = this.ruleForm
        const result = { slotName, appName }
        this.slotList({ pageNo: this.pageNo, pageSize: this.pageSize, slotType: this.slotType, ...result })
        this.$msgSuc('置顶成功')
      } catch (err) {
        this.$msgErr(err.message)
      }
    },

    /**
     * @func 广告位取消置顶
     */
    async slotUnTop(slotKey) {
      try {
        await postSlotUnTop({ slotKey })
        const { slotName, appName } = this.ruleForm
        const result = { slotName, appName }
        this.slotList({ pageNo: this.pageNo, pageSize: this.pageSize, slotType: this.slotType, ...result })
        this.$msgSuc('取消置顶成功')
      } catch (err) {
        console.log(err)
        this.$msgErr(err.message)
      }
    },

    /**
     * @func 复制链接
     */
    handleCapllyLink(slotUrl) {
      this.siteLink = slotUrl
      this.linkVisible = true
    },

    /**
     * @func 查看数据按钮
     */
    viewData(record) {
      const { slotKey, slotType, slotName } = record
      this.$router.push(`/advertising-data?slotKey=${slotKey}&slotType=${slotType}&slotName=${encodeURIComponent(slotName)}`)
    },
    /**
     * @func 关闭模态框
     */
    handleLinked() {
      this.linkVisible = false
    },
    /**
     * @func 置顶当前项
     */
    handleLike(likeStatus, slotKey) {
      if (likeStatus !== 0) {
        // 去掉高亮
        this.slotUnTop(slotKey)
      } else {
        // 加上高亮
        this.slotTop(slotKey)
      }
    },
    /**
     * 查询数据
     */
    submitForm() {
      this.pageNo = 1
      this.pageSize = 10
      const { slotName, appName } = this.ruleForm
      const result = { slotName, appName }
      this.slotList({ pageNo: this.pageNo, pageSize: this.pageSize, ...result })
      console.log(result)
    },
    /**
     * 重置表单
     */
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.slotList({ pageNo: 1, pageSize: 10, slotType: this.slotType })
    },
    /**
     * 打开模态框
     */
    handleAddMedia(title, record) {
      console.log(title)
      if (title === '新建广告位') {
        this.setAdvertising = title
        this.soldOutVisible = false
      } else if (title === '广告位设置') {
        this.setAdvertising = title
        this.soldOutVisible = true
        console.log(record)
        this.AdvertisingForm.slotName = record.slotName
        this.AdvertisingForm.activityRecommendType = record.activityRecommendType + ''
        this.AdvertisingForm.slotKey = record.slotKey
        this.slotKey = record.slotKey
        if (record.activityRecommendType == 1) {
          this.actVisible = false
          const Arr = record.selectedActivities.split(',')
          this.catListValue = Arr.map((item) => {
            return Number(item)
          })
        } else if (record.activityRecommendType == 0) {
          this.actVisible = true
          this.catListValue = []
        }
        if (record.popAdvertType == 1) {
          this.actvalue = ['1']
        } else {
          this.actvalue = []
        }
        if (record.autoDrawAdvert == 1) {
          this.extvalue = ['1']
        } else {
          this.extvalue = []
        }
        if (record.autoChangeActivity == 1) {
          this.cutvalue = ['1']
        } else {
          this.cutvalue = []
        }
        if (record.directAdvertPlan == null || record.directAdvertPlan == 0) {
          this.AdvertisingForm.directAdvertPlan = 'buzhitou'
        } else {
          this.AdvertisingForm.directAdvertPlan = record.directAdvertPlan
        }
      }
      this.queryAppList({ pageNo: 1, pageSize: 100 }) // 查看应用列表
      this.queryCatList() // 查看活动列表
      this.queryAdverPlan({ pageNo: 1, pageSize: 200, types: 1 }) // 查询广告投放计划列表
      this.visible = true
    },
    /**
     * 模态框 - 保存
     */
    async handleOk(e) {
      e.preventDefault()
      if (this.AdvertisingForm.activityRecommendType == 0) {
        this.AdvertisingForm.selectedActivities = ''
      } else if (this.AdvertisingForm.activityRecommendType == 1) {
        this.AdvertisingForm.selectedActivities = this.catListValue.toString()
        if (this.AdvertisingForm.selectedActivities == '') {
          return this.$msgErr('请选择用户可参与的活动!')
        }
      }
      if (this.extvalue.length === 0) {
        this.AdvertisingForm.autoDrawAdvert = 0
      } else {
        this.AdvertisingForm.autoDrawAdvert = 1
      }
      if (this.actvalue.length === 0) {
        this.AdvertisingForm.popAdvertType = 0
      } else {
        this.AdvertisingForm.popAdvertType = 1
      }
      if (this.cutvalue.length === 0) {
        this.AdvertisingForm.autoChangeActivity = 0
      } else {
        this.AdvertisingForm.autoChangeActivity = 1
      }
      if (this.AdvertisingForm.directAdvertPlan == 'buzhitou') {
        this.AdvertisingForm.directAdvertPlan = null
      }

      this.AdvertisingForm.slotType = Number(this.AdvertisingForm.slotType)
      this.AdvertisingForm.materialType = Number(this.AdvertisingForm.materialType)
      this.AdvertisingForm.activityRecommendType = Number(this.AdvertisingForm.activityRecommendType)
      console.log(this.AdvertisingForm)
      try {
        const data = await addSlotUpdate(this.AdvertisingForm)
        this.$msgSuc('成功')
        this.visible = false
        this.emptyData()
        this.slotList({ pageNo: 1, pageSize: this.pageSize, slotType: this.slotType })
      } catch (err) {
        this.$msgErr(err.message)
        this.AdvertisingForm.slotType = this.AdvertisingForm.slotType + ''
        this.AdvertisingForm.materialType = this.AdvertisingForm.materialType + ''
        this.AdvertisingForm.activityRecommendType = this.AdvertisingForm.activityRecommendType + ''
      }
    },
    /**
     * 模态框 - 取消
     */
    handleCancel(formName) {
      console.log('取消')
      this.visible = false
      this.emptyData()
    },
    /**
     * @func 查询应用列表
     */
    async queryAppList(param) {
      try {
        const { data } = await getAppList({ ...param })
        if (data) {
          this.AppListData = data.data.list
        }
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 查询活动列表
     */
    async queryCatList() {
      try {
        const data = await getCatList()
        if (data) {
          this.CatListData = data
        }
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 查询广告投放计划列表
     */
    async queryAdverPlan(param) {
      try {
        const data = await getAdverPlanData({ ...param })
        this.AdverPlanListData = data.list
        console.log(this.AdverPlanListData)
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 确定下架
     */
    async soldOutConfirm() {
      try {
        const data = await soldSlotUpShow({ method: 'update', slotKey: this.slotKey })
        this.visible = false
        this.emptyData()
        this.$msgSuc('下架成功!')
        this.slotList()
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 收入模态框
     * 打开
     */
    handleOpenIncome(record) {
      this.addIncome.sk = record.slotKey
      this.incomeObj.sk = record.slotKey
      this.incomeTitle = record.appName
      this.incomeVisible = true
      this.incomeList(this.incomeObj)
      this.addIncomeVisible = false
    },
    /**
     * 查询收入列表
     */
    async incomeList(param) {
      try {
        const data = await getIncomeList({ ...param })
        if (data) {
          data.list.forEach((item) => {
            item.edit = false
          })
          this.incomeData = data.list
          this.incomeTotal = data.count
          console.log(this.incomeData)
        }
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     *  @func 改变页面值
     */
    handleIncomeCurrentChange(page, pageSize) {
      console.log(page)
      this.incomeObj.pageNo = page
      this.incomeObj.pageSize = pageSize
      this.slotList(this.incomeObj)
    },

    /**
     *  @func 改变页面数据多少
     */
    handleIncomeSizeChange(current, size) {
      this.incomeObj.pageNo = current
      this.incomeObj.pageSize = size
      this.slotList(this.incomeObj)
    },

    /**
     * 新增一行收益数据
     */
    showIncomeBtn() {
      if (this.addIncomeVisible) {
        return this.$msgErr('只能新增一行数据')
      }
      let arr = []
      arr = this.incomeData.filter((item) => {
        return item.edit == true
      })
      if (arr.length != 0) {
        return this.$msgErr('只能同时编辑一行')
      }
      console.log(arr)
      this.addIncomeVisible = true
      this.initSettleTime = moment()
      this.addIncome.slotIncome = ''
      this.addIncome.advertValidClick = 0
    },
    /**
     * 新增收益数据掉接口
     * 保存
     */
    async addIncomeBtn(item) {
      console.log(item)
      console.log(this.initSettleTime)
      if (this.initSettleTime == null) {
        return this.$msgErr('请选择日期')
      }
      if (this.addIncome.advertValidClick == null) {
        return this.$msgErr('请添加次数')
      }
      if (this.addIncome.slotIncome == '') {
        return this.$msgErr('请添加金额')
      }
      if (!item) {
        this.addIncome.id = ''
      }
      let x = Big(this.addIncome.slotIncome)
      const slotIncome = x.times(100)
      this.addIncome.settleTime = moment(this.initSettleTime).format('YYYY-MM-DD')
      const newAddIncome = this.addIncome
      const newObj = {
        ...newAddIncome,
        slotIncome,
      }
      try {
        const data = await AddIncomeList(newObj)
        console.log(data)
        this.$msgSuc('成功!')
        this.addIncomeVisible = false
        this.incomeObj.pageNo = 1
        this.incomeObj.pageSize = 20
        this.incomeList(this.incomeObj)
        this.addIncome.advertValidClick = ''
      } catch (err) {
        this.addIncome.slotIncome = 0
        this.$msgErr(err.message)
      }
    },
    /**
     * 编辑
     */
    editIncome(item) {
      if (this.addIncomeVisible) {
        return this.$msgErr('只能同时编辑一行')
      }
      let arr = []
      arr = this.incomeData.filter((item) => {
        return item.edit == true
      })
      if (arr.length != 0) {
        return this.$msgErr('只能同时编辑一行')
      }
      console.log(arr)

      item.edit = !item.edit

      this.addIncome.slotIncome = item.slotIncome / 100
      this.addIncome.advertValidClick = item.advertValidClick
      this.addIncome.id = item.id
      this.initSettleTime = moment(item.settleTime)
    },
    /**
     * @func 在投计划模态框
     *  取消
     */
    handleProject() {
      this.projectVisible = false
    },

    /**
     *  打开
     */
    handleOpenProject(record) {
      console.log(record.id)
      this._checkId = record.id
      this.projectData = []
      this.selfProjectData = [] // 自动数据
      this.blackListProjectData = [] // 黑名单
      this.blackAdverts = record.blackAdverts // 黑名单id
      this.slotObj.sk = record.slotKey
      this.projectVisible = true
      this.queryAdverList(record.slotKey, record.slotType) // 查询优先计划
      this.rowDrop()
    },
    // 保存
    async saveSlotAdberList() {
      this.slotObj.adverts = []
      this.slotObj.blackAdverts = []
      this.blackListProjectData.forEach((item) => {
        this.slotObj.blackAdverts.push(+item.id)
      })
      this.slotObj.adverts = this.projectData
      console.log(this.slotObj)
      try {
        const data = await postSlotAdberList(this.slotObj)
        this.$msgSuc('成功')
        this.slotList({ pageNo: this.pageNo, pageSize: this.pageSize, slotType: this.slotType })
        this.projectVisible = false
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     * 优先计划拉黑
     */
    planYouXian(record) {
      console.log(record)
      this.projectData.forEach((element, index) => {
        if (element.id == record.id) {
          console.log('选中')
          this.projectData.splice(index, 1)
        }
      })
      this.blackListProjectData.push(record)
    },
    /**
     * 自动排序拉黑
     */
    planZiDong(record) {
      console.log(record)
      this.selfProjectData.forEach((item, index) => {
        if (item.id == record.id) {
          this.selfProjectData.splice(index, 1)
        }
      })
      this.blackListProjectData.push(record)
    },
    /**
     * 恢复投放
     */
    planHuiFu(record) {
      console.log(record)
      this.blackListProjectData.forEach((item, index) => {
        if (item.id == record.id) {
          this.blackListProjectData.splice(index, 1)
        }
      })
      this.selfProjectData.push(record)
    },
    upData(record) {
      console.log(record)
      this.selfProjectData.forEach((item, index) => {
        if (item.id == record.id) {
          this.selfProjectData.splice(index, 1)
        }
      })
      this.projectData.push(record)
    },
    downData(record) {
      console.log(record)
      this.projectData.forEach((item, index) => {
        if (item.id == record.id) {
          this.projectData.splice(index, 1)
        }
      })
      this.selfProjectData.push(record)
    },
    /**
     * @func 查询优先计划
     */
    async queryAdverList(sk, advertType) {
      try {
        const data = await getAdberList({ sk })
        //类型1
        let _filerArr_1 = data.filter((item) => {
          if (item.filterType == 1) {
            if (item.filterSlot) {
              const oldArr = item.filterSlot.split(',')
              const _oldArr = oldArr.map((item) => Number(item))
              if (_oldArr.includes(this._checkId)) {
                return item
              }
            }
          }
        })
        //类型2
        let _filerArr_2 = data.filter((item) => {
          if (item.filterType == 2) {
            if (item.filterSlot) {
              const oldArr = item.filterSlot.split(',')
              const _oldArr = oldArr.map((item) => Number(item))
              if (!_oldArr.includes(this._checkId)) {
                return item
              }
            }
          }
        })
        //类型3
        let _filerArr_3 = data.filter((item) => {
          if (![1, 2].includes(item.filterType)) {
            return item
          }
        })
        const _newArr = [..._filerArr_1, ..._filerArr_2, ..._filerArr_3]
        const startArr = []
        const stopArr = []

        for (let i = 0; i < _newArr.length; i++) {
          if (_newArr[i].planStatus == 1) {
            startArr.unshift(_newArr[i])
          } else {
            stopArr.push(_newArr[i])
          }
        }
        const newArr = [...startArr.reverse(), ...stopArr]
        this.projectData = newArr //优先计划最终赋值
        this.querySlotAdberList({ sk, advertType })
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 查询自定义计划和黑名单
     */
    async querySlotAdberList(param) {
      try {
        const data = await getSlotAdberList({ ...param })
        console.log(data)
        if (this.blackAdverts === null) {
          // 黑名单为空
          // console.log(this.projectData, '优先计划')
          // console.log(data, '自动排序')

          const newid = []
          for (let i = 0; i < data.length; i++) {
            for (let j = 0; j < this.projectData.length; j++) {
              if (data[i].id === this.projectData[j].id) {
                newid.push(data[i].id)
              }
            }
          }
          const newData = data.filter((item) => {
            return !newid.includes(item.id)
          })

          //类型1
          let _filerArr_1 = newData.filter((item) => {
            if (item.filterType == 1) {
              if (item.filterSlot) {
                const oldArr = item.filterSlot.split(',')
                const _oldArr = oldArr.map((item) => Number(item))
                if (_oldArr.includes(this._checkId)) {
                  return item
                }
              }
            }
          })
          //类型2
          let _filerArr_2 = newData.filter((item) => {
            if (item.filterType == 2) {
              if (item.filterSlot) {
                const oldArr = item.filterSlot.split(',')
                const _oldArr = oldArr.map((item) => Number(item))
                if (!_oldArr.includes(this._checkId)) {
                  return item
                }
              }
            }
          })
          //类型3
          let _filerArr_3 = newData.filter((item) => {
            if (![1, 2].includes(item.filterType)) {
              return item
            }
          })
          const _newArr = [..._filerArr_1, ..._filerArr_2, ..._filerArr_3]
          const startArr = []
          const stopArr = []
          for (let i = 0; i < _newArr.length; i++) {
            if (_newArr[i].planStatus == 1) {
              startArr.unshift(_newArr[i])
            } else {
              stopArr.push(_newArr[i])
            }
          }
          const newArr = [...startArr.reverse(), ...stopArr]

          this.selfProjectData = newArr // 自动排序最终赋值
        } else {
          // 黑名单不为空
          const blackAdverArr = this.blackAdverts.split(',')
          const newArr = blackAdverArr.map((item) => Number(item))
          const Arrblack = []
          console.log(newArr)
          console.log(data)
          for (let items in data) {
            for (let newArrindex in newArr) {
              if (data[items].id == newArr[newArrindex]) {
                Arrblack.push(data[items])
              }
            }
          }
          const oldid = []
          for (let i = 0; i < Arrblack.length; i++) {
            for (let j = 0; j < this.projectData.length; j++) {
              if (Arrblack[i].id === this.projectData[j].id) {
                oldid.push(Arrblack[i].id)
              }
            }
          }
          console.log(oldid)
          const oldData = Arrblack.filter((item) => {
            return !oldid.includes(item.id)
          })
          console.log(oldData)
          this.blackListProjectData = oldData

          // -------------
          for (let items in data) {
            for (let blackindex in this.blackListProjectData) {
              if (data[items].id == this.blackListProjectData[blackindex].id) {
                data.splice(items, 1)
              }
            }
          }
          const id = []
          for (let i = 0; i < data.length; i++) {
            for (let j = 0; j < this.projectData.length; j++) {
              if (data[i].id === this.projectData[j].id) {
                id.push(data[i].id)
              }
            }
          }
          const fData = data.filter((item) => {
            return !id.includes(item.id)
          })
          const startArr = []
          const stopArr = []
          for (let i = 0; i < fData.length; i++) {
            if (fData[i].planStatus == 1) {
              startArr.unshift(fData[i])
            } else {
              stopArr.push(fData[i])
            }
          }
          const midArr = [...startArr.reverse(), ...stopArr]

          this.selfProjectData = midArr // 自动排序最终赋值
          console.log(midArr)
        }
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     *@func 广告位类型
     */
    adverTypeChange(value) {
      console.log(value)
      if (value == 0) {
        this.materialVisible = false
        this.AdvertisingForm.materialType = '0'
      } else if (value == 2) {
        this.materialVisible = true
      }
    },
    /**
     * 活动逻辑
     */
    activityRecChange() {
      console.log(this.AdvertisingForm.activityRecommendType)
      if (this.AdvertisingForm.activityRecommendType == 0) {
        this.actVisible = true
      } else if (this.AdvertisingForm.activityRecommendType == 1) {
        this.actVisible = false
      }
    },
    /**
     *  选择用户可参与的活动
     */
    handleChange1(value) {
      this.AdvertisingForm.selectedActivities = this.catListValue.toString()
      console.log(this.AdvertisingForm.selectedActivities)
    },
    /**
     * 置空新增表单
     */
    emptyData() {
      this.AdvertisingForm.slotName = ''
      this.AdvertisingForm.appKey = undefined
      this.AdvertisingForm.slotType = '0'
      this.AdvertisingForm.materialType = '0'
      this.AdvertisingForm.activityRecommendType = '0'
      this.AdvertisingForm.selectedActivities = ''
      this.AdvertisingForm.popAdvertType = 0
      this.AdvertisingForm.autoDrawAdvert = 0
      this.AdvertisingForm.autoChangeActivity = 0
      this.AdvertisingForm.directAdvertPlan = undefined
      this.catListValue = []
      this.actvalue = []
      this.extvalue = []
      this.cutvalue = []
      this.actVisible = true
      this.materialVisible = false
      this.slotKey = ''
    },
  },
}
</script>

<style lang="scss" scoped>
.header {
  width: 100%;
  display: flex;
  flex-direction: row;
}
.my-table {
  margin-top: 20px;
}
::v-deep .pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
::v-deep .el-table .el-table-column {
  background: rgba(249, 245, 245, 1);
}
::v-deep .income {
  width: 100%;
}

.income {
  border-collapse: collapse; /**设置小表格之间的间距为0*/
}
.income tr td {
  border-bottom: 1px solid #eee;
}
.income tr .incomeTd {
  border-bottom: 0px solid #000;
}
.planTable {
  // margin-top: 20px;
}
.planTableRow {
  margin-top: 15px;
}
</style>
